package service

import (
	"wrblog-api-go/app/common/constants"
	"wrblog-api-go/app/common/token"
	"wrblog-api-go/app/dao/dao_sys"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/redis"
	"wrblog-api-go/pkg/status"
	"wrblog-api-go/pkg/utils"
)

func RegisterKey(registerForm token.RegisterForm) (err error) {
	if err = registerForm.RegisterFormValidate(); err != nil {
		return
	}
	privateKey := redis.Get(constants.RSA_KEY + registerForm.RkId)
	pk := utils.RsaDecrypt(registerForm.Pk, privateKey)
	cpk := utils.RsaDecrypt(registerForm.Cpk, privateKey)
	registerForm.Pk = pk
	registerForm.Cpk = cpk
	sysUser, err := dao_sys.GetUserByUk(registerForm.Uk)
	if err != nil {
		return
	}
	if !utils.IsEmpty(sysUser) {
		err = errs.New(status.Conflict, "用户已存在！")
	} else if utils.VerifySpaceUrl(registerForm.Uk) {
		err = errs.New(status.Conflict, "用户已存在！")
	} else {
		ck := redis.Get(constants.CODE_KEY + registerForm.CkId)
		if utils.IsEmpty(ck) {
			err = errs.New(status.PreconditionFailed, "验证码过期！")
		} else if ck != registerForm.Ck {
			err = errs.New(status.PreconditionFailed, "验证码错误！")
		}
	}
	return
}
